package com.shishuo.cms.auth;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.support.RequestContext;

import com.shishuo.cms.constant.UserConstant;
import com.shishuo.cms.entity.UserEntity;
import com.shishuo.cms.entity.UserMenuEntity;
import com.shishuo.cms.exception.AdminLoginException;
import com.shishuo.cms.exception.AuthException;
import com.shishuo.cms.service.UserMenuService;
import com.shishuo.cms.service.UserRoleMenuService;

public class UserAuthInterceptor  extends HandlerInterceptorAdapter
{
	@Autowired
	private UserMenuService userMenuService;
	@Autowired
	private UserRoleMenuService userRoleMenuService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		if (handler.getClass().isAssignableFrom(HandlerMethod.class))
		{
			UserAuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(UserAuthPassport.class);
			//没有声明需要权限,或者声明不验证权限
			if (authPassport == null || authPassport.validate() == false)
				return true;
			else
			{
				//在这里实现自己的权限验证逻辑
				if (UserLogined(request))//如果验证成功返回true（这里直接写false来模拟验证失败的处理）
				{
					if (hasAuth(request))
					{
						return true;
					}
					else
					{
						if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
								.getHeader("X-Requested-With") != null && request
								.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)))
						{
							//返回到登录界面
							response.sendRedirect("/user/noAuth.htm");
						}
						else
						{// JSON格式返回
							RequestContext requestContext = new RequestContext(request);
							throw new AuthException(requestContext.getMessage("system.noAuth"));
						}
						return false;
					}
				}
				else
				//如果验证失败
				{
					//判断是json请求还是html请求
					if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
							.getHeader("X-Requested-With") != null && request
							.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)))
					{
						//返回到登录界面
						response.sendRedirect("/user/login.htm");
					}
					else
					{// JSON格式返回
						RequestContext requestContext = new RequestContext(request);
						throw new AdminLoginException(requestContext.getMessage("user.noLogin"));
					}
					return false;
				}
			}
		}
		else
			return true;
	}

	/**
	 * 验证此用户是否拥有此权限
	 * @param request
	 * @return
	 */
	private boolean hasAuth(HttpServletRequest request)
	{
		String url = request.getRequestURI();
		HttpSession session = request.getSession();
		UserEntity userEntity = (UserEntity) session.getAttribute(UserConstant.SESSION_USER);
		return userRoleMenuService.hasAuthByRoleIdAndUrl(userEntity.getRoleId(), url);
	}

	/**
	 * 验证用户是否已经登陆
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	private boolean UserLogined(HttpServletRequest request) throws Exception
	{
		saveUrlToMenu(request);
		HttpSession session = request.getSession();
		if (null != session.getAttribute(UserConstant.SESSION_USER))
		{
			return true;
		}
		return false;
	}
	private void saveUrlToMenu(HttpServletRequest request) throws Exception
	{
		String url = request.getRequestURI();
		if (!userMenuService.isExist(url))
		{
			UserMenuEntity entity = new UserMenuEntity();
			entity.setMenuName(url);
			entity.setMenuCode(url);
			entity.setMenuUrl(url);
			userMenuService.save(entity);
		}
	}
}
